<template>
  <div class="chart-item-container">
    <div :ref="chartId" class="chart-item"></div>
  </div>
</template>
<script lang="ts">
  import useEcharts from '@/hooks/useEcharts'
  import { defineComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
  import { dispose } from 'echarts/core'
  export default defineComponent({
    name: 'Orderrevenue',
    props: {
      orderRevenueamount: {
        type: Object,
      },
      chartId: {
        type: String,
      },
      title: {
        type: String,
      },
    },
    setup(props) {
      const loading = ref(true)
      const orderrevenue = ref<HTMLDivElement | null>(null)
      const ordernum = ref<HTMLDivElement | null>(null)
      const xaxisdata = ref([])
      const yaxisdata = ref({
        携程: [],
        飞猪: [],
        哈啰: [],
        悟空: [],
        铁行: [],
        滴滴: [],
        飞租: [],
        其他: [],
        自有: [],
      })
      const allTotal = ref([])
      const init = () => {
        const option = {
          color: ['rgba(64, 58, 255)'],
          grid: {
            top: '10%',
            left: '2%',
            right: '2%',
            bottom: '10%',
            containLabel: true,
          },
          legend: {
            selectedMode: false,
            bottom: 0,
            icon: 'circle',
            itemWidth: 10,
            itemHeight: 10,
            itemGap: 15,
            textStyle: {
              fontSize: 12,
              color: '#4E5969',
            },
          },
          xAxis: {
            type: 'category',
            data: xaxisdata.value,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#E5E8EF',
              },
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: '#86909C',
              interval: 0,
              rotate: 40,
            },
          },
          yAxis: {
            type: 'value',
            name: props.chartId === 'orderrevenue' ? '单位（元）' : '单位（个）',
            max: bigNum.value,
            min: smallNum.value,
            interval: (bigNum.value - smallNum.value) / 10,
            nameTextStyle: {
              //  单位样式
              color: '#4E5969', //  字体颜色
              fontSize: 8, //  字体大小
            },
            offset: 13,
            axisLine: {
              show: false,
            },
            axisLabel: {
              color: '#1E1E1E',
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#E5E8EF',
              },
            },
          },
          tooltip: {
            show: true,
            trigger: 'axis',
            formatter(params) {
              const colordata = ref({
                携程: '#00B2FF',
                飞猪: '#FFE180',
                哈啰: '#80E2FF',
                悟空: '#F68B8B',
                铁行: '#56E2A8',
                滴滴: '#546570',
                飞租: '#76C204',
                其他: '#B5C4C8',
                自营: '#246EFF',
              })
              const money = ref(0)
              allTotal.value.map((item) => {
                if (item.date === params[0].axisValue) {
                  money.value = item.data
                }
              })
              let str = `<div class="tooltip-title flexable"><span>${params[0].axisValue}</span>
                <span>${props.chartId === 'orderrevenue' ? '总收益' : '总订单量'}${formatPrice(money.value)}${
                props.chartId === 'orderrevenue' ? '元' : '个'
              }</span></div>`
              for (var i = 0; i < params.length; i++) {
                str += `<div class="content-panel"><span>
                  <span class="circle" style="background: ${colordata.value[params[i].seriesName]}"></span>
                  ${params[i].seriesName}</span><span class="tooltip-value">${params[i].data}${
                  props.chartId === 'orderrevenue' ? '元' : '个'
                }</span></div>`
              }
              return str
            },
            className: 'echarts-tooltip-diy',
          },
          series: [
            {
              name: '携程',
              data: yaxisdata.value['携程'],
              stack: 'one',
              type: 'bar',
              barWidth: 16,
              color: '#00B2FF',
            },
            {
              name: '飞猪',
              data: yaxisdata.value['飞猪'],
              stack: 'one',
              type: 'bar',
              color: '#FFE180',
            },
            {
              name: '哈啰',
              data: yaxisdata.value['哈啰'],
              stack: 'one',
              type: 'bar',
              color: '#80E2FF',
              itemStyle: {
                borderRadius: 2,
              },
            },
            {
              name: '悟空',
              data: yaxisdata.value['悟空'],
              stack: 'one',
              type: 'bar',
              color: '#F68B8B',
              itemStyle: {
                borderRadius: 2,
              },
            },
            {
              name: '铁行',
              data: yaxisdata.value['铁行'],
              stack: 'one',
              type: 'bar',
              color: '#56E2A8',
              itemStyle: {
                borderRadius: 2,
              },
            },
            {
              name: '滴滴',
              data: yaxisdata.value['滴滴'],
              stack: 'one',
              type: 'bar',
              color: '#546570',
              itemStyle: {
                borderRadius: 2,
              },
            },
            {
              name: '飞租',
              data: yaxisdata.value['飞租'],
              stack: 'one',
              type: 'bar',
              color: '#76C204',
              itemStyle: {
                borderRadius: 2,
              },
            },
            {
              name: '其他',
              data: yaxisdata.value['其他'],
              stack: 'one',
              type: 'bar',
              color: '#B5C4C8',
              itemStyle: {
                borderRadius: 2,
              },
            },
            {
              name: '自营',
              data: yaxisdata.value['自有'],
              stack: 'one',
              type: 'bar',
              color: '#246EFF',
              itemStyle: {
                borderRadius: 2,
              },
            },
          ],
        }
        loading.value = false
        if (props.title === '自驾短租收益趋势') {
          nextTick(() => useEcharts(orderrevenue.value as HTMLDivElement)?.setOption(option))
        } else {
          nextTick(() => useEcharts(ordernum.value as HTMLDivElement)?.setOption(option))
        }
      }
      const formatPrice = (price) => {
        return String(price).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
      const updateChart = () => {
        if (props.title === '自驾短租收益趋势') {
          nextTick(() => useEcharts(orderrevenue.value as HTMLDivElement)?.setOption(option))
        } else {
          nextTick(() => useEcharts(ordernum.value as HTMLDivElement)?.setOption(option))
        }
      }
      onMounted(() => {
        init()
        window.addEventListener('resize', () => {
          if (props.title === '自驾短租收益趋势') {
            useEcharts(orderrevenue.value as HTMLDivElement)?.resize()
          } else {
            useEcharts(ordernum.value as HTMLDivElement)?.resize()
          }
        })
      })
      const bigNum = ref(0)
      const smallNum = ref(0)
      watch(
        () => props.orderRevenueamount,
        () => {
          xaxisdata.value = []
          yaxisdata.value = {
            携程: [],
            飞猪: [],
            哈啰: [],
            悟空: [],
            铁行: [],
            滴滴: [],
            飞租: [],
            其他: [],
            自有: [],
          }
          if (props.orderRevenueamount?.channel) {
            props.orderRevenueamount.channel.forEach((item) => {
              if (xaxisdata.value.indexOf(item.date) < 0) {
                xaxisdata.value.push(item.date)
              }
              yaxisdata.value[item.channelName]?.push(item.data)
            })
          }
          if (props.orderRevenueamount?.total) {
            allTotal.value = props.orderRevenueamount.total
            let arr = []
            props.orderRevenueamount.total.forEach((item) => {
              arr.push(item.data)
            })
            let minNum = Math.min.apply(null, arr)
            let maxNum = Math.max.apply(null, arr)

            // 不让最高的值超过最上面的刻度且让显示的刻度是整数
            bigNum.value = Math.ceil(maxNum / 9.5) * 10
            smallNum.value = Math.floor(minNum / 9.5) * 10

            if (bigNum.value == 0 && smallNum.value == 0) {
              bigNum.value = 1000
            }
          }
          if (props.orderRevenueamount?.borderLineList) {
            let minArr = []
            let maxArr = []
            props.orderRevenueamount.borderLineList.forEach((item) => {
              minArr.push(item.negativeNumber)
              maxArr.push(item.positiveNumber)
            })

            let minNum = Math.min.apply(null, minArr)
            let maxNum = Math.max.apply(null, maxArr)

            // 不让最高的值超过最上面的刻度且让显示的刻度是整数
            bigNum.value = Math.ceil(maxNum / 9.5) * 10
            smallNum.value = Math.floor(minNum / 9.5) * 10

            if (bigNum.value == 0 && smallNum.value == 0) {
              bigNum.value = 1000
            }
          }
          init()
        },
        { immediate: true, deep: true }
      )
      onBeforeUnmount(() => {
        if (props.title === '自驾短租收益趋势') {
          dispose(orderrevenue.value as HTMLDivElement)
        } else {
          dispose(ordernum.value as HTMLDivElement)
        }
      })
      return {
        loading,
        orderrevenue,
        ordernum,
        updateChart,
      }
    },
  })
</script>

<style lang="less" scoped>
  .chart-item-container {
    width: 100%;
    height: 380px;
    .chart-item {
      height: 100%;
    }
  }
</style>
